/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nxlv2.nomad.view.ficheClient;

import com.nxlv2.nomad.accessdb.services.ArticleServices;
import com.nxlv2.nomad.accessdb.services.ClientServices;
import com.nxlv2.nomad.accessdb.services.DemandeServices;
import com.nxlv2.nomad.accessdb.services.DetailDemandeServices;
import com.nxlv2.nomad.businessobjects.Adresse;
import com.nxlv2.nomad.businessobjects.Article;
import com.nxlv2.nomad.businessobjects.Client;
import com.nxlv2.nomad.businessobjects.Demande;
import com.nxlv2.nomad.businessobjects.DetailDemande;
import com.nxlv2.nomad.businessobjects.Prix;
import com.nxlv2.nomad.businessobjects.TypeDemande;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.joda.time.DateTime;

/**
 *
 * @author Nastasia
 */
public class FormulaireDemande extends javax.swing.JFrame {

    private final FicheClient fc;
    private final Client cl;
    private ClientServices srvCl = new ClientServices();
    private final Demande dem;

    /**
     * Creates new form FormulaireDemande
     */
    public FormulaireDemande(FicheClient fc, Client cl, Demande dem) {
        initComponents();
        this.fc = fc;
        this.cl = cl;
        this.dem = dem;
        this.setLocationRelativeTo(null);
        initData();
    }

    /**
     * Initialisation informations
     */
    public void initData() {
        if (0 == dem.getIdAppli()) {
            btnSupprimerDetail.setVisible(false);
            lblTitreDemande.setText("Création d'une demande");
        } else {
            lblTitreDemande.setText("Modification de la demande D" + dem.getNumDemande());
            lstTypeDemande.setEnabled(false);
        }
        majAdresses();
        remplirLstArticles();
        lblTotalHT.setText("0");
        lblTVA.setText("0");
        lblTotalTTC.setText("0");
        txtQte.setText("0");
        if (0 != dem.getIdAppli()) {
            remplirFormulaire();
        }
    }

    public void remplirFormulaire() {
        // A compléter
        final DefaultTableModel modelFaco = (DefaultTableModel) jTableAdrFaco.getModel();
        final DefaultTableModel modelLiv = (DefaultTableModel) jTableAdrLiv.getModel();
        for (int i = 0; i < modelFaco.getRowCount(); i++) {
            Adresse adresse = (Adresse) modelFaco.getValueAt(i, 0);
            if (adresse.getIdAppli() == dem.getIdAdresseFacturation()) {
                jTableAdrFaco.getSelectionModel().setSelectionInterval(i, i);
            }
        }
        for (int i = 0; i < modelLiv.getRowCount(); i++) {
            Adresse adresse = (Adresse) modelFaco.getValueAt(i, 0);
            if (adresse.getIdAppli() == dem.getIdAdresseFacturation()) {
                jTableAdrLiv.getSelectionModel().setSelectionInterval(i, i);
            }
        }
        final DefaultTableModel model = (DefaultTableModel) jTableDetail.getModel();
        DetailDemandeServices srvDet = new DetailDemandeServices();
        DemandeServices srvDem = new DemandeServices();
        List<DetailDemande> detailDemandes = srvDem.getDetailDemandes(dem);
        for (DetailDemande detailDemande : detailDemandes) {
            // {{{ COR [type_demande]
            if (detailDemande.getTypeDemande() == dem.getTypeDemande()) {
                Article article = srvDet.getArticle(detailDemande);
                Prix prix = srvDet.getPrix(detailDemande);
                Object[] obj = new Object[]{article, detailDemande.getQuantite(), prix, myRound(Double.valueOf(prix.getPrixUht()).doubleValue() * detailDemande.getQuantite(), 2)};
                model.addRow(obj);
            }
            // COR }}}
        }
        calculTotaux();
    }
    // Remplissages tableaux Adresse 

    public void majAdresses() {
        List<Adresse> adresses = new ArrayList<>();
        int ligneDefault;

        adresses = srvCl.getAdresses(cl);
        final DefaultTableModel modelFaco = (DefaultTableModel) jTableAdrFaco.getModel();
        final DefaultTableModel modelLiv = (DefaultTableModel) jTableAdrLiv.getModel();
        jTableAdrFaco.setDefaultRenderer(Object.class, new TableRenderer());
        jTableAdrLiv.setDefaultRenderer(Object.class, new TableRenderer());
        modelFaco.getDataVector().removeAllElements();
        modelLiv.getDataVector().removeAllElements();

        for (Adresse adresse : adresses) {
            //if (!adresse.isDefaut()) {
            Object[] obj = new Object[]{adresse, adresse.getNomVoie(), adresse.getComplement(),
                adresse.getCodePostal(), adresse.getVille(), adresse.getPays()};
            modelFaco.addRow(obj);
            modelLiv.addRow(obj);
        }
    }
    // Remplissage liste d'articles

    public void remplirLstArticles() {
        List<Article> articles = new ArrayList<Article>();

        lstArticle.removeAllItems();
        articles = srvCl.getArticles(cl);
        for (Article article : articles) {
            lstArticle.addItem(article);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        lblTitreDemande = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableAdrFaco = new javax.swing.JTable();
        lstArticle = new javax.swing.JComboBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableDetail = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTableAdrLiv = new javax.swing.JTable();
        lblTotalHT = new javax.swing.JLabel();
        lblTVA = new javax.swing.JLabel();
        lblTotalTTC = new javax.swing.JLabel();
        lblTotalHT1 = new javax.swing.JLabel();
        lblTVA1 = new javax.swing.JLabel();
        lblTotalTTC1 = new javax.swing.JLabel();
        btnAjoutArticle = new javax.swing.JButton();
        lblArticle = new javax.swing.JLabel();
        btnValider = new javax.swing.JButton();
        txtQte = new javax.swing.JTextField();
        lblArticle1 = new javax.swing.JLabel();
        btnSupprimerDetail = new javax.swing.JButton();
        lstTypeDemande = new javax.swing.JComboBox();
        lblArticle2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Formulaire de création de demande");

        jScrollPane2.setPreferredSize(new java.awt.Dimension(900, 380));

        jPanel2.setPreferredSize(new java.awt.Dimension(900, 380));

        lblTitreDemande.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lblTitreDemande.setText("Création d'une demande");

        jTableAdrFaco.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "N°", "Rue", "Complément", "Code Postal", "Ville", "Pays"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableAdrFaco.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTableAdrFaco);
        jTableAdrFaco.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTableAdrFaco.getColumnModel().getColumn(3).setPreferredWidth(30);
        jTableAdrFaco.getColumnModel().getColumn(5).setPreferredWidth(60);

        lstArticle.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTableDetail.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Article", "Quantité", "Prix UHT", "Prix HT"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableDetail.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableDetail.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTableDetailMousePressed(evt);
            }
        });
        jScrollPane3.setViewportView(jTableDetail);
        jTableDetail.getColumnModel().getColumn(1).setPreferredWidth(10);
        jTableDetail.getColumnModel().getColumn(2).setPreferredWidth(10);
        jTableDetail.getColumnModel().getColumn(3).setPreferredWidth(0);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Adresse de livraison");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Adresse de facturation");

        jTableAdrLiv.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "N°", "Rue", "Complément", "Code Postal", "Ville", "Pays"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableAdrLiv.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane4.setViewportView(jTableAdrLiv);
        jTableAdrLiv.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTableAdrLiv.getColumnModel().getColumn(3).setPreferredWidth(30);
        jTableAdrLiv.getColumnModel().getColumn(5).setPreferredWidth(60);

        lblTotalHT.setText("jLabel3");

        lblTVA.setText("jLabel3");

        lblTotalTTC.setText("jLabel3");

        lblTotalHT1.setText("Total HT :");

        lblTVA1.setText("TVA (20%) :");

        lblTotalTTC1.setText("Total TTC :");

        btnAjoutArticle.setText("Ajouter");
        btnAjoutArticle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAjoutArticleActionPerformed(evt);
            }
        });

        lblArticle.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblArticle.setText("Articles :");

        btnValider.setText("Valider");
        btnValider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValiderActionPerformed(evt);
            }
        });

        txtQte.setText("jTextField1");
        txtQte.setMinimumSize(new java.awt.Dimension(60, 20));
        txtQte.setPreferredSize(new java.awt.Dimension(60, 20));

        lblArticle1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblArticle1.setText("Quantité :");

        btnSupprimerDetail.setText("Supprimer");
        btnSupprimerDetail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSupprimerDetailActionPerformed(evt);
            }
        });

        lstTypeDemande.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Prospect", "Intérêt", "Devis" }));

        lblArticle2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblArticle2.setText("Type de demande :");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addComponent(lblTitreDemande)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btnValider)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(btnSupprimerDetail)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lblTotalHT1))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(lblArticle2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lblTVA1))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(lstTypeDemande, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                                        .addComponent(lblTotalTTC1)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblTotalHT, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblTVA, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblTotalTTC, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addGap(12, 12, 12))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(lblArticle)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblArticle1))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(lstArticle, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtQte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAjoutArticle)))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(lblTitreDemande)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblArticle1)
                            .addComponent(lblArticle))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lstArticle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtQte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAjoutArticle))))
                .addGap(4, 4, 4)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTotalHT1)
                            .addComponent(btnSupprimerDetail)
                            .addComponent(lblTotalHT))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTVA1)
                            .addComponent(lblArticle2)
                            .addComponent(lblTVA))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTotalTTC1)
                            .addComponent(lstTypeDemande, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTotalTTC))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnValider)))
                .addGap(30, 30, 30))
        );

        jScrollPane2.setViewportView(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 950, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private static double myRound(double value, int decimalPlaces) {
        if (decimalPlaces < 0) {
            return value;
        }
        double augmentation = Math.pow(10, decimalPlaces);
        return Math.round(value * augmentation) / augmentation;
    }

    private void calculTotaux() {
        // Calcul des totaux
        final DefaultTableModel model = (DefaultTableModel) jTableDetail.getModel();
        lblTotalHT.setText("0");
        double total = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            total = myRound(Double.valueOf(lblTotalHT.getText()).doubleValue() + Double.valueOf(model.getValueAt(i, 3).toString()).doubleValue(), 2);
            lblTotalHT.setText("" + total);
        }
        lblTVA.setText("" + myRound((Double.valueOf(lblTotalHT.getText()).doubleValue() * 0.20), 2));
        lblTotalTTC.setText("" + myRound(Double.valueOf(lblTotalHT.getText()).doubleValue() + Double.valueOf(lblTVA.getText()).doubleValue(), 2));
        txtQte.setText("0");
        lstArticle.setSelectedItem(null);
    }
    private void btnAjoutArticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAjoutArticleActionPerformed
        // TODO add your handling code here:
        final DefaultTableModel model = (DefaultTableModel) jTableDetail.getModel();
        Article article = (Article) lstArticle.getSelectedItem();
        Pattern p4 = Pattern.compile("^[0-9]*$");
        int error = 0;
        Matcher mQte = p4.matcher(txtQte.getText());
        if (!mQte.matches()) {
            error = 1;
        } else {
            if (0 >= Integer.valueOf(txtQte.getText()).intValue()) {
                error = 1;
            }
        }
        if (null != article && error == 0) {
            // Récupération du prix
            ArticleServices srvArt = new ArticleServices();
            List<Prix> prix = srvArt.getPrix(article);
            Prix prixActuel = new Prix();
            Date dateRecente = new Date();
            int quantite = Integer.valueOf(txtQte.getText()).intValue();
            if (!prix.isEmpty()) {
                for (Prix px : prix) {
                    if (null != dateRecente) {
                        dateRecente = px.getDate();
                        prixActuel = px;
                    } else {
                        if (px.getDate().after(dateRecente)) {
                            dateRecente = px.getDate();
                            prixActuel = px;
                        }
                    }
                }
                // Incrémentation de la quantité si l'article est déjà dans la liste
                boolean existe = false;
                for (int i = 0; i < model.getRowCount(); i++) {
                    Article art = (Article) model.getValueAt(i, 0);
                    if (article.getIdAppli() == art.getIdAppli()) {
                        quantite = quantite + Integer.valueOf(model.getValueAt(i, 1).toString()).intValue();
                        existe = true;
                        model.setValueAt(article, i, 0);
                        model.setValueAt(quantite, i, 1);
                        model.setValueAt(prixActuel.getPrixUht() * quantite, i, 3);
                    }
                }
                // Ajout d'une nouvelle ligne si l'article n'est pas encore dans la liste
                if (false == existe) {
                    Object[] obj = new Object[]{article, quantite, prixActuel, myRound(Double.valueOf(prixActuel.getPrixUht()).doubleValue() * quantite, 2)};
                    model.addRow(obj);
                }
                calculTotaux();
            } else {
                JOptionPane.showMessageDialog(this, "Cet article n'a pas de prix, il ne peut être ajouté à la demande");
            }

        } else {
            if (null == article) {
                JOptionPane.showMessageDialog(this, "Vous n'avez pas sélectionné d'article");
            } else {
                JOptionPane.showMessageDialog(this, "La quantité doit être supérieure à 0");
            }
        }
    }//GEN-LAST:event_btnAjoutArticleActionPerformed

    private void jTableDetailMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableDetailMousePressed
    }//GEN-LAST:event_jTableDetailMousePressed

    private void btnSupprimerDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSupprimerDetailActionPerformed
        // TODO add your handling code here:
        if (0 <= jTableDetail.getSelectedRow()) {
            final DefaultTableModel model = (DefaultTableModel) jTableDetail.getModel();
            model.removeRow(jTableDetail.getSelectedRow());
            calculTotaux();
        } else {
            JOptionPane.showMessageDialog(this, "Vous n'avez pas sélectionné de ligne à supprimer");
        }
    }//GEN-LAST:event_btnSupprimerDetailActionPerformed

    private void btnValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValiderActionPerformed
        // TODO add your handling code here:
        TypeDemande typeDemande = TypeDemande.getByLibelle(lstTypeDemande.getSelectedItem().toString());
        if (0 < jTableDetail.getRowCount()) {
            if (0 > jTableAdrFaco.getSelectedRow()) {
                JOptionPane.showMessageDialog(this, "Vous n'avez pas sélectionné l'adresse de facturation");
            } else if (0 > jTableAdrLiv.getSelectedRow()) {
                JOptionPane.showMessageDialog(this, "Vous n'avez pas sélectionné l'adresse de livraison");
            } else {
                Adresse adresseFaco = (Adresse) jTableAdrFaco.getValueAt(jTableAdrFaco.getSelectedRow(), 0);
                Adresse adresseLiv = (Adresse) jTableAdrLiv.getValueAt(jTableAdrLiv.getSelectedRow(), 0);
                Article article = new Article();
                Article art = new Article();
                Prix prix = new Prix();
                Prix prx = new Prix();
                List<DetailDemande> detailDemandes;
                DetailDemande detailDemande = new DetailDemande();
                DemandeServices srvDem = new DemandeServices();
                DetailDemandeServices srvDet = new DetailDemandeServices();
                boolean detailExist = false;
                // {{{ COR [type_demande]
                if (0 == dem.getIdAppli() && dem.getTypeDemande() != typeDemande) {
                    // Création de demande
                    dem.setDate(new DateTime().toDate());
                    dem.setTypeDemande(typeDemande);
                    dem.setNumDemande(new DateTime().toDate().getTime());
                    dem.setIdAdresseFacturation(adresseFaco.getIdAppli());
                    dem.setIdAdresseLivraison(adresseLiv.getIdAppli());
                    srvDem.create(dem, cl);
                    for (int i = 0; i < jTableDetail.getRowCount(); i++) {
                        detailDemande.setQuantite(Integer.valueOf(jTableDetail.getValueAt(i, 1).toString()).intValue());
                        detailDemande.setTypeDemande(typeDemande);
                        article = (Article) jTableDetail.getValueAt(i, 0);
                        prix = (Prix) jTableDetail.getValueAt(i, 2);
                        srvDet.create(detailDemande, dem);
                        srvDet.linkArticle(article, detailDemande);
                        srvDet.linkPrix(prix, detailDemande);
                    }
                } else {
                    // Modification de demande
                    dem.setIdAdresseFacturation(adresseFaco.getIdAppli());
                    dem.setIdAdresseLivraison(adresseLiv.getIdAppli());
                    srvDem.update(dem);

                    detailDemandes = srvDem.getDetailDemandes(dem);
                    for (int i = 0; i < jTableDetail.getRowCount(); i++) {
                        detailExist = false;
                        article = (Article) jTableDetail.getValueAt(i, 0);
                        prix = (Prix) jTableDetail.getValueAt(i, 2);
                        for (DetailDemande detDem : detailDemandes) {
                            if (detDem.getTypeDemande() == dem.getTypeDemande()) {
                                art = srvDet.getArticle(detDem);
                                if (art.getIdAppli() == article.getIdAppli()) {
                                    detDem.setQuantite(Integer.valueOf(jTableDetail.getValueAt(i, 1).toString()).intValue());
                                    //detDem.setTypeDemande(typeDemande);
                                    srvDet.update(detDem);
                                    detailExist = true;
                                }
                            }
                        }
                        if (false == detailExist) {
                            detailDemande.setQuantite(Integer.valueOf(jTableDetail.getValueAt(i, 1).toString()).intValue());
                            //detailDemande.setTypeDemande(typeDemande);
                            srvDet.create(detailDemande, dem);
                            srvDet.linkArticle(article, detailDemande);
                            srvDet.linkPrix(prix, detailDemande);
                        }
                    }
                    for (DetailDemande detDem : detailDemandes) {
                        Boolean exist = false;
                        if (detDem.getTypeDemande() == dem.getTypeDemande()) {
                            Article artDet = srvDet.getArticle(detDem);
                            for (int i = 0; i < jTableDetail.getRowCount(); i++) {

                                Article artTab = (Article) jTableDetail.getValueAt(i, 0);
                                if (artDet.getIdAppli() == artTab.getIdAppli()) {
                                    exist = true;
                                }
                            }
                            if(exist == false){
                                srvDet.delete(detDem);
                                System.out.println("supprimer ligne "+ detDem +" qui a l article "+ artDet);
                            }
                        }
                    }
                }
                // COR }}}
                FicheDetailDemande fdd = new FicheDetailDemande(fc, cl, dem, null);
                fdd.setVisible(true);
                fc.majDemandes();
                fc.majCommandes();
                dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Vous n'avez pas mis d'articles dans le détail de la demande");
        }
    }//GEN-LAST:event_btnValiderActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAjoutArticle;
    private javax.swing.JButton btnSupprimerDetail;
    private javax.swing.JButton btnValider;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTableAdrFaco;
    private javax.swing.JTable jTableAdrLiv;
    private javax.swing.JTable jTableDetail;
    private javax.swing.JLabel lblArticle;
    private javax.swing.JLabel lblArticle1;
    private javax.swing.JLabel lblArticle2;
    private javax.swing.JLabel lblTVA;
    private javax.swing.JLabel lblTVA1;
    private javax.swing.JLabel lblTitreDemande;
    private javax.swing.JLabel lblTotalHT;
    private javax.swing.JLabel lblTotalHT1;
    private javax.swing.JLabel lblTotalTTC;
    private javax.swing.JLabel lblTotalTTC1;
    private javax.swing.JComboBox lstArticle;
    private javax.swing.JComboBox lstTypeDemande;
    private javax.swing.JTextField txtQte;
    // End of variables declaration//GEN-END:variables
}
